<template>
  <a-modal
    title="发票"
    width="45%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :footer="null"
    @cancel="handleCancel"
    destroyOnClose
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="发票号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-input
            disabled
            v-decorator="['invoiceNum',
                          {
                            rules: [{required: false, message: '请输入发票号'}],
                            initialValue: invoiceNum
                          }]"
          />
        </a-form-item>
<!--        <a-form-item-->
<!--          label="发票"-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol">-->

<!--          <a-upload-->
<!--            name="mediaFile"-->
<!--            :showUploadList="false"-->
<!--            :multiple="true"-->
<!--            :before-upload="beforeUploadFile"-->
<!--          >-->
<!--            <a-button :loading="uploadLoading">-->
<!--              <a-icon type="upload"/>添加发票-->
<!--            </a-button>-->
<!--          </a-upload>-->
<!--        </a-form-item>-->
      </a-form>
      <div class="table-operator">
        <a-button
          :disabled="!invoiceSelectedRowKeys.length"
          
          type="primary"
          style="margin-bottom: 8px"
          icon="download"
          @click="exportInvoiceZip"
        >导出</a-button>
      </div>

      <a-table
        :columns="invoiceColumns"
        :data-source="filenameList"
        :row-selection="{ onChange: onInvoiceSelectChange }"
        :pagination="false"
        :scroll="{ x: true}"
      >
<!--          <span-->
<!--            slot="action"-->
<!--            slot-scope="text, record">-->
<!--            <template>-->
<!--              <a-popconfirm-->
<!--                placement="left"-->
<!--                title="确定删除这条数据吗？"-->
<!--                ok-text="确定"-->
<!--                cancel-text="取消"-->
<!--                @confirm="doDeleteInvoice(record)"-->
<!--              >-->
<!--                <a>删除</a>-->
<!--              </a-popconfirm>-->
<!--            </template>-->
<!--          </span>-->
        <span
          slot="invoiceFileName"
          slot-scope="text, record">
            <template>
              <span>{{record.invoiceName}}</span>
            </template>
          </span>
        <span
          slot="invoiceName"
          slot-scope="text, record">
            <template>
              <a @click="handlePreview(record.invoiceUrl)">{{record.invoiceName}}</a>
            </template>
          </span>
      </a-table>
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancelimg">
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage" />
    </a-modal>
    <export-file
      @cancel="handleExportCancel"
      :url="invoiceExportUrl"
      :status="invoiceExportStatus"
      :visible="invoiceExportVisible"
    >
    </export-file>
    </a-spin>
  </a-modal>
</template>
<script>
import { addInvoiceNum, uploadProjectFile, exportInvoiceZip, exportInvoiceZipResult} from '@/api/manage'
import config from '@/config/defaultSettings'
import exportFile from './exportFile'
export default {
  name: 'EditMail',
  components: {
    exportFile
  },
  data() {
    return {
      invoiceImage: '',
      form: this.$form.createForm(this),
      mailAddrs: {},
      type: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      visible: false,
      confirmLoading: false,
      timer: null,
      time: 90,
      isNewPhoneModal: true,

      //发票
      filenameList: [],
      imageUrlPrefix: config.uploadedUrlPrefix,
      uploadLoading: false,
      invoiceKey : 1,
      invoiceNum: '',
      previewVisible: false,
      previewImage: '',

      invoiceColumns: [{
        title: '发票图像',
        dataIndex: 'invoiceName',
        scopedSlots: {customRender: 'invoiceName'},
        // width: '100px'
        // fixed: 'left'
      },
        {
          title: '发票文件名称',
          dataIndex: 'invoiceFileName',
          scopedSlots: {customRender: 'invoiceFileName'}
          // fixed: 'left'
        }
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   width: '80px',
        //   scopedSlots: {customRender: 'action'},
        //   fixed: 'right'
        // }
        ],

      invoiceExportTime: '',
      invoiceExportUrl: '',
      invoiceExportStatus: 0,
      invoiceExportVisible: false,
      invoiceSelectedRowKeys: [],
    }
  },
  created() {},
  methods: {
    show(record) {
      console.log(record)
      if (record.invoiceImage) {
        this.invoiceImage = record.invoiceImage
        this.filenameList = this.invoiceImage.split(',').map(fileUrl =>{
          return {
            key : this.invoiceKey++,
            invoiceName : fileUrl.indexOf('@@@')===-1?fileUrl:fileUrl.split('@@@')[1],
            invoiceUrl: fileUrl
          }
        })
      } else {
        this.invoiceImage = ''
        this.filenameList = []
      }
      this.invoiceNum = record.invoiceNum ? record.invoiceNum : ''
      this.mailAddrs = record.batchId
      this.visible = true
    },

    handleCancelimg() {
      this.previewVisible = false
      this.previewImage = ''
    },
    handlePreview(url) {
      if(url.split('.')[url.split('.').length-1] == 'pdf'){
        window.open(this.isHttpString(url)?url:this.imageUrlPrefix + url)
        return
      }
      this.previewVisible = true
      this.previewImage = this.isHttpString(url)?url:this.imageUrlPrefix + url
    },
    handleCancel() {
      this.visible = false
    },
    handleSubmit() {
      this.form.validateFields((err, value) => {
        if (!err) {
          value.invoiceImage = this.filenameList.map(item => item.invoiceUrl).join(',')
          console.log(value, 1)
          addInvoiceNum(this.mailAddrs, value).then(res => {
            console.log(res)
            this.handleCancel()
            this.$emit('onSuccess')
          })
        }
      })
    },
    beforeUploadFile(file) {
      console.log(file,1)
      this.file = file
      this.handleFileUpload('invoiceImage')
      return false
    },
    handleFileUpload(fieldName) {
      const formData = new FormData()
      formData.append('mediaFile', this.file)
      this.uploadLoading = true
      uploadProjectFile(formData)
        .then(res => {
          const fileUrl = res.resData && res.resData.result
          const filename = fileUrl.indexOf('@@@')==-1?fileUrl:fileUrl.split('@@@')[1]
          this.filenameList.push({
            key: this.invoiceKey++,
            'invoiceName': filename,
            'invoiceUrl': fileUrl})
        })
        .catch(() => {
          this.$message.error('上传失败，请重试')
        })
        .finally(() => {
          this.uploadLoading = false
        })
    },
    doDeleteInvoice(record){
      this.filenameList = this.filenameList.filter(item => record.key !== item.key)
      console.log(this.filenameList)
    },

    onInvoiceSelectChange(invoiceSelectedRowKeys,invoiceSelectedRows) {
      console.log('selectedRowKeys changed: ', invoiceSelectedRowKeys,invoiceSelectedRows)
      this.invoiceSelectedRowKeys = invoiceSelectedRows.map(item => item.invoiceUrl)
    },

    // 导出发票文件
    exportInvoiceZip() {
      this.invoiceExportVisible = true
      exportInvoiceZip({ invoiceUrls: this.invoiceSelectedRowKeys }).then(res => {
        if (res.resCode == '0000') {
          this.exportInvoiceZipResult(res.resData.id)
        } else {

        }
      }).catch(err => {

      })

    },
    // 查询导出状态
    exportInvoiceZipResult(id) {
      exportInvoiceZipResult({ id: id }).then(res => {
        if (this.invoiceExportVisible == false) {
          clearTimeout(this.time)
          return
        }
        if (res.resCode == '0000') {
          if (res.resData.status == 0) {
            this.invoiceExportStatus = 0
            this.invoiceExportTime = setTimeout(() => {
              this.exportInvoiceZipResult(id)
            }, 3000)
          } else {
            this.invoiceExportStatus = 1
            this.invoiceExportUrl = res.resData.downloadUrl
            clearTimeout(this.time)
          }
        }

      }).catch(err => {

      })
    },
    handleExportCancel(e) {
      clearTimeout(this.invoiceExportTime)
      this.invoiceExportVisible = false
    }
  }
}
</script>

<style>
.addbillimgbox {
  position: relative;
}
.addbillimg {
  width: 100%;
}
.addclose {
  position: absolute;
  right: 0;
  top: -10px;
}
</style>
